<?PHP
	$host = $_REQUEST['host'];
//	$date = date("h:m:s",strtotime($_REQUEST['date']));
	$date = $_REQUEST['date'];
	$data = explode("\n",$_REQUEST['data']);
	foreach($data as $line){
		if(preg_match("#^(\d{1,3}) packets transmitted, (\d{1,3}) received, (\d{1,3})% packet loss, time (\d{1,5})ms$#",$line,$packets) ||
			preg_match("#^rtt min/avg/max/mdev = (\d{1,5}[\..]\d{1,3}.)/(\d{1,5}[\..]\d{1,3}.)/(\d{1,5}[\..]\d{1,3}.)/(\d{1,5}[\..]\d{1,3}.) ms#",$line,$delay)){
			
			if(sizeof($packets) > 1){
				$loss = round($packets[3]);
				$loss>0 ? $color="\033[31m" : $color="";
				echo"$date - $color$loss% loss\033[37m - ";
			}
			
			if(sizeof($delay) > 1){
				$min = $delay[1];
				$avg = $delay[2];
				$max = $delay[3];
				$mdev= $delay[4];
				echo"\033[36m $min / \033[32m $avg / \033[31m $max / \033[35m $mdev \033[37m ";
			}elseif($loss==100){
				$min=0; $avg=0; $max=0; $mdev=0;
			}
			
			unset($packets);
			unset($delay);
		}else
			echo"Line didn't match any regex.\n$line\n";
		
		if(isset($host,$min,$avg,$max,$mdev,$loss)){
			$db_host = "localhost";
			$db_user = "root";
			$db_password = "";
			$db_database_name = "BSST";
			$mysqli = new MySQLi($db_host,$db_user,$db_password,$db_database_name);
			if($mysqli->query("INSERT INTO BSST.ping (host,min,avg,max,mdev,loss) VALUES ('$host',$min,$avg,$max,$mdev,$loss)"))
				echo"\033[32m-O-\033[37m\n";
			else echo $mysqli->error;
		}
	}
?>